#include "RocketExtendProcessor.h"
#include "Bullet.h"
#include "BaseObject.h"
#include "MainLayer.h"
#include "MathUtil.h"

#define VELOCITY_DEFAULT ccp(0, 600)
#define ANGLE_DELTA_DEG 5


RocketExtendProcessor::RocketExtendProcessor(void)
{
	_currentTime = 0;
	_state = 0;
	_lockTarget = NULL;
}


RocketExtendProcessor::~RocketExtendProcessor(void)
{
	CC_SAFE_RELEASE(_lockTarget);
}

void RocketExtendProcessor::processing( float dt )
{
	float timeDelay2 = 1.0f;
	Bullet* target = dynamic_cast<Bullet*>(getTarget());

	if (_state == 0 && target->getVelocity().y > 0)
	{
		target->setIsRotateByDirect(true);
		target->setAcceleration(CCPointZero);
		target->setVelocity(VELOCITY_DEFAULT);
		_state = 1;
	} else if (_state == 1 && _currentTime > timeDelay2)
	{
		BaseObject* lockTarget = findTarget();
		if (!lockTarget)
			return;

		CCPoint direct = lockTarget->getPositionCenter() - target->getPositionCenter();
		float rad = MathUtil::angle2Vetor(target->getVelocity(), direct);

		if (rad < 0)
			target->setVelocity(MathUtil::rotateVector(target->getVelocity(), MathUtil::DegreeToRad(-ANGLE_DELTA_DEG)));
		else
			target->setVelocity(MathUtil::rotateVector(target->getVelocity(), MathUtil::DegreeToRad(ANGLE_DELTA_DEG)));
	}


	_currentTime += dt;
}

void RocketExtendProcessor::onEnter()
{
	ExtendBaseProcessor::onEnter();
	setTarget(getParent());
	schedule(SEL_SCHEDULE(&RocketExtendProcessor::processing));
}

void RocketExtendProcessor::onExit()
{
	ExtendBaseProcessor::onExit();
	unschedule(SEL_SCHEDULE(&RocketExtendProcessor::processing));
	removeFromParent();
}

BaseObject* RocketExtendProcessor::findTarget()
{
	CCArray* listEnemy = dynamic_cast<BaseObject*>(getTarget())->getMainLayer()->getEnemies();

	CCObject* it;
	if (_lockTarget && listEnemy->containsObject(_lockTarget))
		return _lockTarget;
	BaseObject* lockTarget = NULL;
	float minDistance = -1;
	CCARRAY_FOREACH(listEnemy, it)
	{
		BaseObject* enemy = dynamic_cast<Enemy*>(it);
		float distance = MathUtil::absVector(enemy->getPosition() - getTarget()->getPosition());
		if (minDistance == -1)
		{
			minDistance = distance;
			lockTarget = enemy;
		}

		if (distance < minDistance)
		{
			minDistance = distance;
			lockTarget = enemy;
		}
	}

	setLockTarget(lockTarget);
	return lockTarget;
}
